package cqie.cn.frame.shirospringboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 王林
 * @version 1.0
 * @date 2021-09-10 周五
 * @time 20:20
 * @description
 */
@Controller
public class Mycontroller {

    @RequestMapping({"/", "/index"})
    public String toIndex(Model model) {
        model.addAttribute("msg", "hello shiro!!!");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add() {

        return "add";
    }

    @RequestMapping("/user/update")
    public String update() {

        return "update";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username, String password, Model model) {
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        // 执行登录方法，如果没有异常就说明 OK 了
        try {
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {

            model.addAttribute("msg", "用户名错误！！！");
            return "login";
        } catch (IncorrectCredentialsException e) {

            model.addAttribute("msg", "密码错误！！！");
            return "login";
        }
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unAuthorized() {
        return "未授权无法访问此页面";
    }


}
